package rdw;

import java.awt.AWTException;
import java.io.IOException;

import rdw.http.HttpServer;
import rdw.robot.RemoteRobot;
import rdw.ui.AlertDialog;
import rdw.ui.MenuCallback;
import rdw.ui.SystrayIcon;

/**
 * RDWApp is the main class for the RDW Application.
 */
public class RDWApp implements MenuCallback
{
	private static final int DEFAULT_PORT = 8082;

	private RemoteRobot robot;
	private HttpServer httpServer;

	public RDWApp(int port)
	{
		// create RemoteRobot
		try
		{
			robot = new RemoteRobot();
		}
		catch (AWTException e)
		{
			AlertDialog.showAlert("Remote Desktop Web", "Unable to start mouse and keyboard simluation.");
			e.printStackTrace();
			System.exit(1);
		}
		
		// create and start HTTP Server thread
		createHttpServer(port);
		
		// create Systray Icon
		@SuppressWarnings("unused")
		SystrayIcon systray = new SystrayIcon(this);
	}
	
	public void createHttpServer(int port)
	{
		try
		{
			httpServer = new HttpServer(port, this.robot);
			httpServer.start();
		}
		catch (IOException e)
		{
			AlertDialog.showAlert("Remote Desktop Web", "Unable to start HTTP server on port " + Integer.toString(port) + ".");
			e.printStackTrace();
			System.exit(1);
		}	
	}
	
	public void changePort(int port)
	{
		if (httpServer.getPort() != port)
		{
			httpServer.shutdown();
			createHttpServer(port);
		}
	}
	
	public int getPort()
	{
		return httpServer.getPort();
	}
	
	public String getBoundIps()
	{
		return httpServer.getBoundIps();
	}

	public static void main(String[] args)
	{
		int port = RDWApp.DEFAULT_PORT;
		
		if (args.length == 1)
		{
			port = Integer.parseInt(args[0]);
		}
		
		@SuppressWarnings("unused")
		RDWApp app = new RDWApp(port);
	}
}
